package cn.zhouyafeng.itchat4j.talk;

import cn.zhouyafeng.itchat4j.api.MessageTools;
import cn.zhouyafeng.itchat4j.core.Core;
import cn.zhouyafeng.itchat4j.utils.HttpClientUtil;
import cn.zhouyafeng.itchat4j.utils.MyHttpClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
public class TXTalk {

    static  MyHttpClient myHttpClient = Core.getInstance().getMyHttpClient();
    static HttpClientUtil httpClientUtil = new HttpClientUtil();
    private static final String appId = "2108522437";
    private static final String appKey = "zwQQqtijli8p46ER";

    private static final String TALK_URL = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat";

    /**
     * 智能闲聊
     * @param userId
     * @param question
     * @return
     * @throws Exception
     */
    public static String talk(String userId,String question) {
        String str = "神游中。。";
        userId = userId.replaceAll("@","");
        if(userId.length() > 32){
            userId = userId.substring(0,31);
        }
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("app_id",appId);
            map.put("session",userId);
            map.put("time_stamp",System.currentTimeMillis()/1000);
            map.put("nonce_str",System.currentTimeMillis());
            map.put("question",question);
            map.put("sign",getSign(map));

//            long begin = System.currentTimeMillis();
////            JSONObject result = httpClientUtil.post(TALK_URL,map,new TypeReference<JSONObject>() {});
//
//            HttpEntity entity = myHttpClient.doPost(TALK_URL, JSON.toJSONString(map));
//            JSONObject result = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));

            long begin = System.currentTimeMillis();
            JSONObject result = httpClientUtil.post(TALK_URL,map,new TypeReference<JSONObject>() {});
            log.info("结果{},耗时{}",result,System.currentTimeMillis() - begin);
            if(result != null){
                return result.getJSONObject("data").getString("answer");
            }

        }catch (Exception e){
            e.printStackTrace();
            log.error("腾讯智能闲聊异常{}",e.getMessage());
        }

        return str;
    }


    public static void main(String[] args) {
//        String s = talk("@@5d6b501d53451f1defd28482a89bc5f1e442a100d489211e69b1771c06f2b57f","liam温州天气");
//        System.out.println(s);





    }


    /**
     * 将<key, value>请求参数对按key进行字典升序排序，得到有序的参数对列表N
     * 将列表N中的参数对按URL键值对的格式拼接成字符串，得到字符串T（如：key1=value1&key2=value2），URL键值拼接过程value部分需要URL编码，URL编码算法用大写字母，例如%E8，而不是小写%e8
     * 将应用密钥以app_key为键名，组成URL键值拼接到字符串T末尾，得到字符串S（如：key1=value1&key2=value2&app_key=密钥)
     * 对字符串S进行MD5运算，将得到的MD5值所有字符转换成大写，得到接口请求签名
     * @return
     */
    protected static  String getSign(Map<String,Object> param) throws Exception {
        if(param != null && param.size() > 0){
            List<String> keys = new ArrayList<>(param.keySet());
            Collections.sort(keys);
            StringBuffer str = new StringBuffer();
            for(String s : keys){
                str.append(s).append("=").append(getURLEncoderString(param.get(s).toString())).append("&");
            }
            str.append("app_key=").append(appKey);
            String reult = DigestUtils.md5Hex(str.toString()).toUpperCase();
            return reult;

        }
        return null;
    }


    private static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

}
